package com.dmall.recursion;

/**
 * 使用递归求一个整型数组的和
 * @author xiao1.wang@dmall.com
 * @date 2019-03-24 00:08:33
 */
public class RecursionSummary {

    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5, 6, 7, 8};
        int sum = sum(arr);
        System.out.println("sum = " + sum);
    }

    public static int sum(int[] arr) {
        return sum(arr, 0);
    }

    private static int sum(int[] arr, int l) {
        if (l < 0) {
            throw new IllegalArgumentException("Array index must greater than zero.");
        }

        if (l >= arr.length) {
            return 0;
        }

        return arr[l] + sum(arr, l + 1);
    }
}
